package com.jvtd.demo.amap;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationQualityReport;
import com.jvtd.base.JvtdActivity;
import com.jvtd.demo.R;
import com.jvtd.gd_location.JvtdLocation;
import com.jvtd.gd_location.JvtdLocationCallBack;
import com.jvtd.gd_location.utils.ForegroundUtil;
import com.jvtd.widget.toast.JvtdToast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class GdBackgroundLocationActivity extends JvtdActivity implements View.OnClickListener
{

  private TextView tvResult;
  private Button btnStartLocation;
  private JvtdToast mToast;

  private static final int NOTIFICATION_ID = 0x11;

  @Override
  protected void bindView()
  {
    TextView tvTitle = findViewById(R.id.tv_title);
    tvTitle.setText("高德后台定位模块");
    Toolbar mToolbar = findViewById(R.id.tool_bar);
    setToolbar(mToolbar, true);

    btnStartLocation = findViewById(R.id.bt_location);
    btnStartLocation.setOnClickListener(this);
    Button btnStartBackgroundLocation = findViewById(R.id.bt_enableBackground);
    btnStartBackgroundLocation.setOnClickListener(this);
    Button btnStopBackgroundLocation = findViewById(R.id.bt_disableBackground);
    btnStopBackgroundLocation.setOnClickListener(this);
    tvResult = findViewById(R.id.tv_result);
  }

  @Override
  protected void getLayout()
  {
    setContentView(R.layout.activity_gd_background_location);
  }

  @Override
  protected void initViewAndData()
  {
    mToast = new JvtdToast(this, JvtdToast.FLAG_BOTTOM);

    JvtdLocation.getInstance(this).setApiKey("707fb1ed21b6b4ba91d71cb818f3b805").init(new JvtdLocationCallBack()
    {
      @Override
      public void onLocationChanged(AMapLocation location)
      {
        StringBuilder sb = new StringBuilder();
        sb.append("定位成功" + "\n");
        sb.append("定位类型: ").append(location.getLocationType()).append("\n");
        sb.append("经    度    : ").append(location.getLongitude()).append("\n");
        sb.append("纬    度    : ").append(location.getLatitude()).append("\n");
        sb.append("精    度    : ").append(location.getAccuracy()).append("米").append("\n");
        sb.append("提供者    : ").append(location.getProvider()).append("\n");

        sb.append("速    度    : ").append(location.getSpeed()).append("米/秒").append("\n");
        sb.append("角    度    : ").append(location.getBearing()).append("\n");
        // 获取当前提供定位服务的卫星个数
        sb.append("星    数    : ").append(location.getSatellites()).append("\n");
        sb.append("国    家    : ").append(location.getCountry()).append("\n");
        sb.append("省            : ").append(location.getProvince()).append("\n");
        sb.append("市            : ").append(location.getCity()).append("\n");
        sb.append("城市编码 : ").append(location.getCityCode()).append("\n");
        sb.append("区            : ").append(location.getDistrict()).append("\n");
        sb.append("区域 码   : ").append(location.getAdCode()).append("\n");
        sb.append("地    址    : ").append(location.getAddress()).append("\n");
        sb.append("地    址    : ").append(location.getDescription()).append("\n");
        sb.append("兴趣点    : ").append(location.getPoiName()).append("\n");
        //定位完成的时间
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        Date date = new Date(location.getTime());
        String dateStr = df.format(date);
        sb.append("定位时间: ").append(dateStr).append("\n");
        sb.append("***定位质量报告***").append("\n");
        sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" : "关闭").append("\n");
        sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
        sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
        sb.append("****************").append("\n");

        //解析定位结果，
        String result = sb.toString();
        tvResult.setText(result);
      }

      @Override
      public void locationError(int errorCode, String errorInfo)
      {
        //定位失败
        //解析定位结果，
        String result = ("定位失败" + "\n") +
                "错误码:" + errorCode + "\n" +
                "错误信息:" + errorInfo + "\n";
        tvResult.setText(result);
      }

      @Override
      public void onCustomError(String errorInfo)
      {
        mToast.showMessage("errorInfo = " + errorInfo, 500);
      }
    });
  }

  /**
   * 获取GPS状态的字符串
   */
  private String getGPSStatusString(int statusCode)
  {
    String str = "";
    switch (statusCode)
    {
      case AMapLocationQualityReport.GPS_STATUS_OK:
        str = "GPS状态正常";
        break;
      case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
        str = "手机中没有GPS Provider，无法进行GPS定位";
        break;
      case AMapLocationQualityReport.GPS_STATUS_OFF:
        str = "GPS关闭，建议开启GPS，提高定位质量";
        break;
      case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
        str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
        break;
      case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
        str = "没有GPS定位权限，建议开启gps定位权限";
        break;
    }
    return str;
  }

  @Override
  public void onClick(View view)
  {
    switch (view.getId())
    {
      case R.id.bt_location:
        if (btnStartLocation.getText().equals("开始定位"))
        {
          btnStartLocation.setText("停止定位");
          tvResult.setText("正在定位...");
          startLocation();
        } else
        {
          btnStartLocation.setText("开始定位");
          stopLocation();
          tvResult.setText("定位停止");
        }
        break;

      case R.id.bt_enableBackground:
        //启动后台定位
        JvtdLocation.getInstance(this).enableBackgroundLocation(NOTIFICATION_ID, buildNotification());
        break;

      case R.id.bt_disableBackground:
        //关闭后台定位
        JvtdLocation.getInstance(this).disableBackgroundLocation(true);
        break;
    }
  }

  private void startLocation()
  {
    JvtdLocation.getInstance(this).startLocation();
  }

  private void stopLocation()
  {
    JvtdLocation.getInstance(this).stopLocation();
  }

  @Override
  protected void onResume()
  {
    super.onResume();
    JvtdLocation.getInstance(this).disableBackgroundLocation(true);
  }


  @Override
  protected void onStop()
  {
    super.onStop();
    boolean isBackground = ForegroundUtil.isBackground(getApplicationContext());
    //如果app已经切入到后台，启动后台定位功能
    if (isBackground)
      JvtdLocation.getInstance(this).enableBackgroundLocation(NOTIFICATION_ID, buildNotification());
  }

  @Override
  protected void onDestroy()
  {
    super.onDestroy();
    JvtdLocation.getInstance(this).closeLocationOption();
    JvtdLocation.getInstance(this).stopLocation();
    JvtdLocation.getInstance(this).destoryLocation();
  }

  //----------------------------------------------------------------------------------------------------------------------------------
  //------------------------------------------------------创建通知栏--------------------------------------------------------------------
  //----------------------------------------------------------------------------------------------------------------------------------
  private static final String NOTIFICATION_CHANNEL_NAME = "BackgroundLocation";
  private NotificationManager notificationManager = null;
  boolean isCreateChannel = false;

  @SuppressLint("NewApi")
  private Notification buildNotification()
  {
    Notification.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
      //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
      if (null == notificationManager)
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      String channelId = getPackageName();
      if (!isCreateChannel)
      {
        NotificationChannel notificationChannel = new NotificationChannel(channelId, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
        notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
        notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
        notificationManager.createNotificationChannel(notificationChannel);
        isCreateChannel = true;
      }
      builder = new Notification.Builder(getApplicationContext(), channelId);
    } else
      builder = new Notification.Builder(getApplicationContext());

    builder.setSmallIcon(R.mipmap.icon_logo)
            .setContentTitle(getString(R.string.app_name))
            .setContentText("正在后台运行")
            .setWhen(System.currentTimeMillis());
    return builder.build();
  }

}
